// 全局变量
const API_ENDPOINTS = {
    totalComparison: '/api/comparison/total',
    rankComparison: '/api/comparison/rank',
    ageComparison: '/api/comparison/age',
    apiData: '/api/api-data',
    dbData: '/api/db/data'
};

// 工具函数
const formatNumber = (num) => {
    return new Intl.NumberFormat('zh-CN').format(num);
};

const showLoading = () => {
    document.getElementById('loading').style.display = 'flex';
};

const hideLoading = () => {
    document.getElementById('loading').style.display = 'none';
};

const showError = (message) => {
    const container = document.querySelector('.toast-container');
    const toastId = `toast-${Date.now()}`;
    
    const toastHtml = `
        <div class="toast show" id="${toastId}">
            <div class="toast-header">
                <i class="fas fa-exclamation-circle text-danger me-2"></i>
                <strong class="me-auto">错误提示</strong>
                <button type="button" class="btn-close" onclick="document.getElementById('${toastId}').remove()"></button>
            </div>
            <div class="toast-body">
                ${message}
            </div>
        </div>
    `;
    
    container.insertAdjacentHTML('beforeend', toastHtml);
    
    // 5秒后自动关闭
    setTimeout(() => {
        const toast = document.getElementById(toastId);
        if (toast) toast.remove();
    }, 5000);
    
    console.error(message);
};

// 数据加载函数
const loadTotalComparison = async () => {
    try {
        const response = await fetch(API_ENDPOINTS.totalComparison);
        if (!response.ok) throw new Error('加载总人数对比数据失败');
        const result = await response.json();
        
        if (!result.success) {
            throw new Error(result.error || '获取数据失败');
        }

        const data = result.data;
        const tbody = document.getElementById('total-comparison');
        tbody.innerHTML = `
            <tr>
                <td>API数据</td>
                <td>${formatNumber(data.api_total)}</td>
                <td>
                    <span class="difference-badge ${data.matched ? 'success' : 'danger'}">
                        ${data.matched ? '无差异' : `差异: ${Math.abs(data.api_total - data.db_total)}人`}
                    </span>
                </td>
                <td>
                    <button class="btn btn-sm btn-outline-primary" onclick="viewApiDetails()">
                        查看详情
                    </button>
                </td>
            </tr>
            <tr>
                <td>数据库数据</td>
                <td>${formatNumber(data.db_total)}</td>
                <td>-</td>
                <td>
                    <button class="btn btn-sm btn-outline-primary" onclick="viewDbDetails()">
                        查看详情
                    </button>
                </td>
            </tr>
        `;
    } catch (error) {
        showError(error.message);
    }
};

const loadRankComparison = async () => {
    try {
        const tbody = document.getElementById('rank-comparison');
        
        // 清空现有内容
        tbody.innerHTML = `
            <tr>
                <td colspan="4">
                    <div class="loading-container">
                        <div class="loading-spinner"></div>
                        <div class="loading-text">正在加载数据</div>
                    </div>
                </td>
            </tr>
        `;

        const response = await fetch(API_ENDPOINTS.rankComparison);
        if (!response.ok) throw new Error('加载职级分布对比数据失败');
        const result = await response.json();
        
        if (!result.success) {
            throw new Error(result.error || '获取数据失败');
        }

        const data = result.data;
        const allSeries = ['P序列', 'M序列', 'B序列'];
        let html = '';

        allSeries.forEach(series => {
            const apiData = data.api_data[series] || {};
            const dbData = data.db_data[series] || {};
            const allLevels = new Set([...Object.keys(apiData), ...Object.keys(dbData)]);

            if (allLevels.size > 0) {
                // 添加序列标题
                html += `
                    <tr class="table-secondary">
                        <td colspan="4"><strong>${series}</strong></td>
                    </tr>
                `;

                // 添加每个职级的数据
                Array.from(allLevels).sort().forEach(level => {
                    const apiCount = apiData[level] || 0;
                    const dbCount = dbData[level] || 0;
                    const difference = Math.abs(apiCount - dbCount);
                    const matched = apiCount === dbCount;

                    html += `
                        <tr class="${matched ? '' : 'table-warning'}">
                            <td>${level}</td>
                            <td>${apiCount}人</td>
                            <td>${dbCount}人</td>
                            <td>
                                <span class="difference-badge ${matched ? 'success' : 'danger'}">
                                    ${matched ? '无差异' : `差异: ${difference}人`}
                                </span>
                            </td>
                        </tr>
                    `;
                });
            }
        });

        if (html === '') {
            html = `
                <tr>
                    <td colspan="4" class="text-center">暂无数据</td>
                </tr>
            `;
        }

        tbody.innerHTML = html;
    } catch (error) {
        showError(error.message);
    }
};

// 详情查看函数
const viewApiDetails = async () => {
    try {
        showLoading();
        const response = await fetch(API_ENDPOINTS.apiData);
        if (!response.ok) throw new Error('加载API详情数据失败');
        const data = await response.json();
        // TODO: 实现详情展示逻辑
        hideLoading();
    } catch (error) {
        hideLoading();
        showError(error.message);
    }
};

const viewDbDetails = async () => {
    try {
        showLoading();
        const response = await fetch(API_ENDPOINTS.dbData);
        if (!response.ok) throw new Error('加载数据库详情数据失败');
        const data = await response.json();
        // TODO: 实现详情展示逻辑
        hideLoading();
    } catch (error) {
        hideLoading();
        showError(error.message);
    }
};

const viewLevelDetails = async (level, type) => {
    try {
        showLoading();
        const endpoint = type === 'api' ? '/api/personnel/api' : '/api/personnel/db';
        const response = await fetch(`${endpoint}?level=${level}`);
        if (!response.ok) throw new Error(`加载${type.toUpperCase()}职级详情数据失败`);
        const data = await response.json();
        // TODO: 实现详情展示逻辑
        hideLoading();
    } catch (error) {
        hideLoading();
        showError(error.message);
    }
};

// 初始化函数
const initializeApp = async () => {
    try {
        showLoading();
        await Promise.all([
            loadTotalComparison(),
            loadRankComparison()
        ]);
        hideLoading();
    } catch (error) {
        hideLoading();
        showError(error.message);
    }
};

// 事件监听
document.getElementById('refreshData')?.addEventListener('click', async (e) => {
    e.preventDefault();
    await initializeApp();
});

// 启动应用
document.addEventListener('DOMContentLoaded', initializeApp); 